﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

namespace BToolkit
{
    public class VersionChecker : MonoBehaviour
    {
        private static VersionChecker _instance;
        public static VersionChecker Instance
        {
            get
            {
                if (!_instance)
                {
                    _instance = GameObject.FindObjectOfType<VersionChecker>();
                    if (!_instance)
                    {
                        GameObject go = new GameObject("VersionChecker");
                        DontDestroyOnLoad(go);
                        _instance = go.AddComponent<VersionChecker>();
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// 有版本更新则回调下载地址url,没有更新回调null
        /// </summary>
        public void CheckVersion(string jsonUrl, Action<string> Callback)
        {
            StartCoroutine(DoDownload(jsonUrl, Callback));
        }

        IEnumerator DoDownload(string jsonUrl, Action<string> Callback)
        {
            UnityWebRequest webRequest = UnityWebRequest.Get(jsonUrl);
            yield return webRequest.SendWebRequest();
            if (webRequest.error != null)
            {
                Debuger.LogError("CheckVersion Error:" + webRequest.error);
                yield break;
            }
            try
            {
                JObject json = JObject.Parse(webRequest.downloadHandler.text);
                string version = (string)json["versionName"];

                Debuger.Log("版本比较：" + GetAppInfo.GetAppVersionName() + " = " + version + "url:" + jsonUrl);

                if (!GetAppInfo.GetAppVersionName().Equals(version))
                {
                    string url = (string)json["url"];
                    Callback(url);
                }
                else
                {
                    Callback(null);
                }
            }
            catch (Exception err)
            {
                Callback(null);
                Debuger.LogError("CheckVersion Error:" + err);
            }
            Destroy(gameObject);
        }

    }
}